<template>
  <bd-popup
    class="custom"
    popupId="lotteryV3WinningResult"
    :weights="4"
    v-model:show="props.show"
    :style="{
      'background-color': 'transparent',
      padding: '0 24px 30px 24px !important',
    }"
    :overlay-style="{ background: 'rgba(0, 0, 0, 0.5)' }"
    zIndex="999999"
    teleport="body"
    :close-on-click-overlay="false"
  >
    <!-- 标题 -->
    <div class="title">
      <img
        v-if="!lotteryStore.isFri"
        class="title-bg"
        src="/image/lottery-v3/winningResult-title.svg"
      />
      <img
        v-else
        class="title-bg"
        src="/image/lottery-v3/winningResult-title1.svg"
      />
      <div class="title-text">
        {{
          $t(
            source && source.hashScore
              ? isWinning
                ? "lotteryMoney.gxzjl"
                : "lotteryMoney.zjjg"
              : "lotteryMoney.kjz"
          )
        }}
      </div>
    </div>
    <div class="box">
      <!-- 开奖号码 -->
      <div class="header" :class="{ 'header-fri': lotteryStore.isFri }">
        <div class="header-text">{{ $t("lotteryMoney.kjNums") }}</div>
        <div v-if="source && source.hashScore" class="header-nums items-center">
          <div
            v-for="(item, index) in source.hashScore.split('')"
            :key="index"
            class="header-nums-item items-center"
          >
            <img
              v-if="!lotteryStore.isFri"
              class="header-nums-item-bg"
              src="/image/lottery-v3/num-zj-bg1.svg"
            />
            <img
              v-else
              class="header-nums-item-bg"
              src="/image/lottery-v3/num-zjfri-bg1.svg"
            />
            <div class="header-nums-item-text">{{ item }}</div>
          </div>
        </div>
        <div v-else class="header-nums items-center">
          <div
            v-for="(item, index) in [
              'LUCKY',
              'LUCKY',
              'LUCKY',
              'LUCKY',
              'LUCKY',
            ]"
            :key="index"
            class="header-nums-item"
          >
            <img
              v-if="!lotteryStore.isFri"
              class="header-nums-item-bg"
              src="/image/lottery-v3/num-zj-bg1.svg"
            />
            <img
              v-else
              class="header-nums-item-bg"
              src="/image/lottery-v3/num-zjfri-bg1.svg"
            />
            <div class="header-nums-item-text header-nums-item-text-lucky">
              {{ item }}
            </div>
          </div>
        </div>
      </div>
      <!-- 信息 -->
      <div class="content">
        <img
          class="content-left"
          src="/image/lottery-v3/result-content-icon.svg"
        />
        <div class="content-center">
          <div
            class="content-center-top items-center"
            :style="{
              'justify-content':
                source && source.hashScore && isWinning
                  ? 'space-between'
                  : 'flex-start',
            }"
          >
            <!-- 待开奖描述 -->
            <div v-if="source && !source.hashScore" class="content-desc">
              {{ $t("lotteryMoney.kjzIng") }}
            </div>
            <!-- 下注号码 -->
            <div class="content-item-box">
              <div
                class="content-item items-center"
                v-for="(item, index) in userPrizeDetailArr"
                :key="index"
                :class="{
                  'content-item-bm0': index + 1 == userPrizeDetailArr.length,
                }"
              >
                <div class="content-item-left items-center">
                  <div
                    class="content-item-left-item"
                    v-for="(num, index) in item.drawNoArr"
                    :key="index"
                  >
                    <img
                      v-if="num.include && !lotteryStore.isFri"
                      class="content-item-left-item-bg"
                      src="/image/lottery-v3/num-zj-bg1.svg"
                    />
                    <img
                      v-else-if="num.include && lotteryStore.isFri"
                      class="content-item-left-item-bg"
                      src="/image/lottery-v3/num-zjfri-bg1.svg"
                    />
                    <img
                      v-else
                      class="content-item-left-item-bg"
                      src="/image/lottery-v3/num-xz-bg1.svg"
                    />
                    <div
                      class="content-item-left-item-num"
                      :class="{
                        'content-item-left-item-num-zj': num.include,
                      }"
                    >
                      {{ num.str }}
                    </div>
                  </div>
                  <div class="content-item-left-drawCount">
                    *{{ item.drawCount }}
                  </div>
                </div>
                <div class="content-item-right items-center">
                  <!-- 待开奖 -->
                  <template v-if="!source.hashScore">
                    <div class="content-item-right-title">
                      {{ $t("lotteryMoney.kjz") }}
                    </div>
                    <img
                      class="content-item-right-icon"
                      src="/image/lottery-v3/result-djs-icon.svg"
                    />
                  </template>
                  <!-- 中奖信息 -->
                  <template v-else>
                    <div class="items-center">
                      <div>
                        <div class="content-item-right-title">
                          {{ prizeLevelText(item.prizeLevel) }}
                        </div>
                        <div
                          v-if="item.prizeLevel == 3 || item.prizeLevel == 50"
                          class="content-item-right-value"
                          :class="{
                            'content-item-right-value-fri': lotteryStore.isFri,
                          }"
                        >
                          +{{
                            toThousands(
                              decimalToLength(
                                Number(item.oneBetPrizeAmount) *
                                  Number(item.drawCount)
                              )
                            )
                          }}
                          BDC
                        </div>
                      </div>
                      <img
                        v-if="item.prizeLevel == 1"
                        class="content-item-right-img"
                        src="/image/lottery-v3/result-ydj-icon.svg"
                      />
                      <img
                        v-else-if="item.prizeLevel == 2"
                        class="content-item-right-img"
                        src="/image/lottery-v3/result-edj-icon.svg"
                      />
                      <img
                        v-else-if="item.prizeLevel == 3"
                        class="content-item-right-img"
                        src="/image/lottery-v3/result-sdj-icon.svg"
                      />
                      <img
                        v-else-if="item.prizeLevel == 50"
                        class="content-item-right-img"
                        src="/image/lottery-v3/result-cyj-icon.svg"
                      />
                      <div v-else class="content-item-right-img"></div>
                    </div>
                  </template>
                </div>
              </div>
            </div>
            <!-- 奖金描述,开奖以后展示 -->
            <div v-if="source && source.hashScore && isWinning">
              <div class="content-center-top-footer items-center">
                <img
                  v-if="lotteryStore.isFri"
                  class="content-center-top-footer-icon"
                  src="/image/title-yellow-icon.svg"
                />
                <img
                  v-else
                  class="content-center-top-footer-icon"
                  src="/image/title-blue-icon.svg"
                />
                <div class="content-center-top-footer-text">
                  {{ $t("lotteryMoney.jldesc1") }}
                </div>
              </div>
              <div class="content-center-top-footer items-center">
                <img
                  v-if="lotteryStore.isFri"
                  class="content-center-top-footer-icon"
                  src="/image/title-yellow-icon.svg"
                />
                <img
                  v-else
                  class="content-center-top-footer-icon"
                  src="/image/title-blue-icon.svg"
                />
                <div class="content-center-top-footer-text">
                  {{ $t("lotteryMoney.jldesc2") }}
                </div>
              </div>
            </div>
          </div>
          <!-- 按钮 -->
          <div class="content-center-bottom items-center">
            <!-- 重试/刷新 -->
            <div
              v-if="
                (isThreeSeconds || lotteryStore.$state.isThredFailSocket) &&
                source &&
                !source.hashScore
              "
              class="content-center-bottom-item"
              :class="{
                'content-center-bottom-item-fri': lotteryStore.isFri,
              }"
              @click.stop="confirm(3)"
            >
              {{ $t("lotteryMoney.refresh") }}
            </div>
            <template v-else>
              <!-- 分享给好友 -->
              <div
                v-if="source && source.hashScore && isWinning"
                class="content-center-bottom-item content-center-bottom-item-maxwidth"
                :class="{
                  'content-center-bottom-item-fri': lotteryStore.isFri,
                }"
                @click.stop="confirm(2)"
              >
                {{ $t("lotteryMoney.fxghy") }}
              </div>
              <!-- 继续下注 -->
              <div
                class="content-center-bottom-item"
                :class="{
                  'content-center-bottom-item-maxwidth':
                    source && source.hashScore && isWinning,
                  'content-center-bottom-item-fri': lotteryStore.isFri,
                }"
                @click.stop="confirm(1)"
              >
                {{ $t("lotteryMoney.jxxz") }}
              </div>
            </template>
          </div>
        </div>
        <img
          class="content-right"
          src="/image/lottery-v3/result-content-icon.svg"
        />
      </div>
    </div>
    <!-- 关闭 -->
    <img
      class="close"
      src="/image/close-fff-icon.svg"
      @click.stop="closePopup"
    />
  </bd-popup>
</template>
<script setup lang="ts" name="winningResultPopup">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useClipboard } from "@vueuse/core";
import { useLotteryV3Store } from "~/store/modules/lottery-v3";
import { useGlobalStore } from "~~/store/global";

interface betNumInfo {
  // 记录id
  id?: string;
  // 下注数量
  drawCount?: string | number;
  // 号码
  drawNo: string;
  // 下注时间
  drawTime?: string;
  // 奖金类型 0:无奖金 1:BDC 2:美金
  prizeType?: string | number;
  // 每注奖金数量, 可能为空或者不返回key
  oneBetPrizeAmount?: string;
  // 获奖等级 0:未中奖/未开奖 1:一等奖 2:二等奖 3:三等奖 50:参与奖
  prizeLevel?: string | number;
  // 中奖状态 1:未开奖 2:未中奖 3:奖励待发放 4:奖励已发放
  prizeStatus: string | number;
}

interface WinningMessage {
  sid?: string;
  nickname?: string;
  avatar?: string;
  hashScore?: string; // 开奖号码
  sessionId?: string; // 抽奖期数id
  transactionHash?: string; // 链上hash
  orderNo: string; //  内部订单号
  detailList: betNumInfo[]; // 下注号码列表
}

const props = withDefaults(
  defineProps<{
    show: boolean;
    source: WinningMessage; // 中奖消息
  }>(),
  {
    show: false,
    source: {
      sessionId: "",
      detailList: [
        {
          drawNo: "LUCKY",
          prizeStatus: 1,
        },
      ],
    },
  }
);

const emit = defineEmits(["update:show", "winningCall", "refresh"]);

const lotteryStore = useLotteryV3Store();

const { t } = useI18n();

const globalStore = useGlobalStore();
// 资源
const file = getOssFileUrl({
  avatarDefault: "/image/avatar-default.png",
  sharePage: "/invite-friends/v3/invite",
});

// 分享地址
const shareUrl = computed(() => {
  return (
    file.sharePage +
    "?hiddenBar=1" +
    `&language=${globalStore.$state.language}` +
    `&packageId=${globalStore.$state.packageId}` +
    `&sourceType=12` +
    `&code=${lotteryStore.$state.inviteLotteryCode}`
  );
});

// 是否中奖了,不包含参与奖
const isWinning = computed(() => {
  if (props.source && props.source.hashScore) {
    let isWinning = false;
    props.source.detailList.forEach((e) => {
      if (
        Number(e.prizeLevel) < 50 &&
        Number(e.prizeLevel) >= 1 &&
        !isWinning
      ) {
        isWinning = true;
      }
    });
    return isWinning;
  }
  return false;
});
// 奖项
const prizeLevelText = (val: any) => {
  if (val == 1) {
    return t("lotteryMoney.ydj");
  } else if (val == 2) {
    return t("lotteryMoney.edj");
  } else if (val == 3) {
    return t("lotteryMoney.sdj");
  } else if (val == 50) {
    return t("lotteryMoney.cyj");
  } else {
    return t("lotteryMoney.wzj");
  }
};

/**
 * @description: 匹配中奖号码
 * 1. 重复出现的数字,要根据数量显示
 * @param {*} a 中奖号码
 * @param {*} b 下注号码
 * @return {*} c 下注号码,与中奖号码匹配的结果
 * @author: zhj1214
 */
const includesNumToArr = (a: string, b: string) => {
  const charMapA = new Map();

  // 构建字符映射表，记录字符在 a 中的数量
  for (let char of a) {
    charMapA.set(char, (charMapA.get(char) || 0) + 1);
  }

  let c = [];
  for (let char of b) {
    const countInA = charMapA.get(char);
    if (countInA && countInA > 0) {
      c.push({ str: char, include: true });
      charMapA.set(char, countInA - 1);
    } else {
      c.push({ str: char, include: false });
    }
  }
  return c;
};

const userPrizeDetailArr = computed(() => {
  if (
    props.source &&
    props.source.detailList &&
    props.source.detailList.length > 0
  ) {
    // 1. 号码维度,进行聚合,去重复
    let drawNoObj: any = {};
    const list = JSON.parse(JSON.stringify(props.source.detailList));
    list.forEach((e: any) => {
      if (drawNoObj[e.drawNo]) {
        drawNoObj[e.drawNo].drawCount =
          Number(drawNoObj[e.drawNo].drawCount) + Number(e.drawCount || 1);
      } else {
        drawNoObj[e.drawNo] = e;
      }
    });
    const drawNoList = Object.values(drawNoObj);
    // console.log("drawNoList:===", drawNoList);
    // 2. 匹配中奖号码
    return drawNoList.map((e: any) => {
      e.drawNoArr = includesNumToArr(props.source.hashScore || "", e.drawNo);
      return e;
    });
  }
  return [];
});

// 是否已经展示了三秒了
const isThreeSeconds = ref(false);
let isThreeSecondsTimer: any = null;
onMounted(() => {
  isThreeSecondsTimer = setTimeout(() => {
    isThreeSeconds.value = true;
  }, 3000);
});
onBeforeUnmount(() => {
  isThreeSecondsTimer && clearTimeout(isThreeSecondsTimer);
});

// 关闭弹窗
const closePopup = () => {
  // 1. 关闭时间发现,socket 断开了; 则需要重新连接
  if (lotteryStore.$state.isThredFailSocket) {
    emit("refresh", 2);
  }
  // 2. 关闭,并判断是否需要展示：领取免费卡
  emit("refresh", 3);
};

/****************** 分享 ******************/
const saveCopy = () => {
  if (!file.sharePage) return;
  const { copy, isSupported } = useClipboard({
    source: "",
  });
  if (!isSupported.value) {
    showToast({
      message: t("mvp.other.bzcjtb"),
      "z-index": 9999999,
    });
  } else {
    copy(shareUrl.value);
    showToast({
      message: t("mvp.other.fzcg"),
      "z-index": 9999999,
    });
  }
};

let shareLoading = false;
const firebase = useInitFirebase(); // 初始化firebase
const shareApp = () => {
  if (shareLoading) return;
  try {
    shareLoading = true;
    saveCopy();
    console.log("分享地址:", shareUrl.value);
    bridge.onShare(t("lotteryMoney.hyzldmfcj"), shareUrl.value);
    firebase?.logEvent("BDC_H5_LotteryV3_inviteFriends_shareApp_Click"); // 埋点访问
  } catch (error) {
    console.log(error);
  } finally {
    // 延时 1s，防止用户连续点击
    setTimeout(() => {
      shareLoading = false;
    }, 1000);
  }
};

/****************** 按钮逻辑 ******************/

/**
 * @description: 按钮逻辑: 1,继续下注 2,分享好友 3,关闭
 */
const confirm = (val: number) => {
  if (val == 1) {
    emit("winningCall");
    closePopup();
  } else if (val == 2) {
    shareApp();
    closePopup();
  } else if (val == 3) {
    emit("refresh", 1);
  }
};
</script>
<style lang="scss" scoped>
.title {
  position: relative;

  width: 100%;
  justify-content: center;
  &-bg {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 0;
    width: 304 * 2px;
    height: 30 * 2px;
  }
  &-text {
    position: relative;
    z-index: 9;
    height: 30 * 2px;
    line-height: 30 * 2px;
    text-align: center;

    color: #fff;
    font-size: 15 * 2px;
    font-weight: 590;
  }
}
.box {
}
.header {
  padding: 4 * 2px 21 * 2px;
  border-radius: 12 * 2px 12 * 2px 0px 0px;
  background: linear-gradient(90deg, #01b2ff 0%, #0180ff 100%);
  &-fri {
    background: linear-gradient(89deg, #f8b100 0%, #fd9b04 100%);
  }

  &-text {
    text-align: center;
    margin-bottom: 2 * 2px;
    color: rgba(255, 255, 255, 0.7);
    font-size: 11 * 2px;
    font-weight: 400;
  }
  &-nums {
    justify-content: space-between;

    &-item {
      width: 48 * 2px;
      height: 48 * 2px;
      line-height: 48 * 2px;
      border-radius: 8 * 2px;
      background: linear-gradient(180deg, #e5fbff 0%, #fff 100%);
      justify-content: center;
      position: relative;

      &-bg {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 36 * 2px;
        height: 36 * 2px;
      }
      &-text {
        position: relative;
        z-index: 9;
        color: #fff;
        font-size: 20 * 2px;
        font-weight: 590;
        text-align: center;
        &-lucky {
          font-size: 8 * 2px;
        }
      }
    }
  }
}
.content {
  display: flex;
  justify-content: space-between;

  &-desc {
    text-align: center;
    color: #999da7;
    font-size: 13 * 2px;
    margin-bottom: 10 * 2px;
  }

  &-left {
    position: relative;
    width: 8 * 2px;
    height: 8 * 2px;
  }
  &-center {
    background-color: #fff;
    width: 100%;
    border-bottom-left-radius: 12 * 2px;
    border-bottom-right-radius: 12 * 2px;
    &-top {
      padding: 10 * 2px;
      min-height: 308 * 2px;
      flex-direction: column;
      justify-content: flex-start;

      &-footer {
        margin-top: 10 * 2px;
        &-icon {
          margin-right: 6 * 2px;
          width: 9 * 2px;
          height: 9 * 2px;
        }
        &-text {
          font-size: 11 * 2px;
          color: #999da7;
          font-weight: 400;
        }
      }
    }
    &-bottom {
      padding: 12 * 2px 10 * 2px;
      justify-content: space-between;
      &-item {
        position: relative;
        height: 36 * 2px;
        line-height: 36 * 2px;
        text-align: center;
        width: 100%;

        color: #fff;
        font-size: 15 * 2px;
        font-weight: 590;
        border-radius: 4 * 2px;
        background: #007bff;
        &-free {
          position: absolute;
          top: -8 * 2px;
          right: 0;
          border-radius: 4 * 2px;
          border-bottom-right-radius: 0;
          color: #fff;
          font-size: 12 * 2px;
          font-weight: 510;
          background: #ff4040;
          padding: 2.5 * 2px 6 * 2px;
          height: 16 * 2px;
          line-height: 10 * 2px;
        }

        &-fri {
          background: #ff9b01;
        }

        &-maxwidth {
          max-width: calc(50% - 5 * 2px);
        }
        &-close {
          color: #141924;
          border-radius: 4 * 2px;
          border: 1px solid #e8eaf0;
          background: #fff;
        }
      }
    }
  }
  &-right {
    position: relative;
    top: 0;
    transform: rotateY(180deg);
    width: 8 * 2px;
    height: 8 * 2px;
  }
  &-item {
    justify-content: space-between;
    padding: 0 10 * 2px;
    height: 44 * 2px;
    border-radius: 8 * 2px;
    border: 0.7px solid #e3effd;
    background: #fff;
    margin-bottom: 10 * 2px;

    &-bm0 {
      margin-bottom: 0;
    }

    &-box {
      width: 100%;
    }

    &-left {
      justify-content: center;
      &-item {
        position: relative;
        width: 18 * 2px;
        height: 18 * 2px;
        margin-right: 2 * 2px;

        &-bg {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        &-num {
          position: relative;
          z-index: 9;
          line-height: 18 * 2px;
          text-align: center;
          color: #8e96a4;
          font-size: 13 * 2px;
          font-weight: 590;

          &-zj {
            color: #fff;
          }
        }
      }
      &-drawCount {
        color: #141924;
        font-size: 12 * 2px;
      }
    }
    &-right {
      &-title {
        color: #141924;
        font-size: 12 * 2px;
        text-align: right;
      }
      &-icon {
        margin-left: 4 * 2px;
        width: 24 * 2px;
        height: 24 * 2px;
      }
      &-value {
        text-align: right;
        color: #007bff;
        font-size: 12 * 2px;
        font-weight: 590;
        margin-top: 2 * 2px;
        &-fri {
          color: #ff9b01;
        }
      }
      &-img {
        margin-left: 4 * 2px;
        width: 24 * 2px;
        height: 24 * 2px;
      }
    }
  }
}
.close {
  position: relative;
  z-index: 9;
  bottom: -30 * 2px;
  left: 50%;
  transform: translateX(-50%);
  width: 30 * 2px;
  height: 30 * 2px;
}
</style>
